<?php

namespace app\api\controller;

use app\admin\model\Goods as GoodsModel;
use app\admin\model\Usercoupon as Usercoupon;
use app\admin\model\Cart as Cart;
use app\common\controller\Api;
use app\common\model\Authentication;
use EasyWeChat\Factory;
use think\Cache;
use think\Config;
use think\Db;
use think\Env;
use think\Log;
use think\Validate;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['selfaction', 'reearnest','sellearnest'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

        $this->Goods = new GoodsModel;
        $this->Order = new \app\admin\model\Order();
        $this->Usercoupon = new Usercoupon;
        $this->Cart = new Cart;
    }

    /**
     * 订单列表
     */
    public function index()
    {
        $userid = $this->auth->id;
        $orders = $this->Order;
        $is_seller = request()->param('is_seller');
        if($is_seller == 2){
            $orders = $orders->where('user_id', $userid);
        }else{
            $orders = $orders->where('seller_id', $userid);
        }
        $status = request()->param('status');
        if ($status) {
            $orders = $orders->where('status', '=', $status);
        }
        $limit = request()->param('limit', 20);
        $orders = $orders->order('createtime', 'desc')->paginate($limit);
        $this->success('请求成功', [
            'orders' => $orders,
        ]);
    }

    /**
     * 详情
     */
    public function detail()
    {
        $order_id = request()->param('order_id');
        if (!$order_id) {
            $this->error('参数不全');
        }
        $order = $this->Order
            ->with(['user', 'seller', 'good'])
            ->where('id', '=', $order_id)->find();
        $this->success('订单详情', $order);
    }

    /**
     * 直接下单
     */
    public function add()
    {
        $user = $this->auth->getUser();
        $data = request()->param();
        if (empty($data['good_id']) || empty($data['name']) || empty($data['phone'])) {
            $this->error('参数不全');
        }
        if (!Validate::regex($data['phone'], "^1\d{10}$")) {
            $this->error(__('请输入正确的手机号'));
        }
        $log = Authentication::where('user_id',$user['id'])->where('is_attestation',2)->find();
        if(!$log) $this->error('请先进行实名认证');
        $good = $this->Goods->where('id', $data['good_id'])->find();
        if (!$good || $good['status'] != 1) {
            $this->error(__('商品不存在或已下架'));
        }
        $cache = Cache::get($data['good_id']);
        if($cache){
            $this->error(__('商品已售完'));
        }
        Cache::set($data['good_id'],$data['good_id'],3);
        if($good['is_seller'] == 1){
            //卖出
            //买家定金比例
            $earnest = Config::get('site.earnest');
            //买家抽成比例
            $data['buyer_commission'] = Config::get('site.buyer_commission');
            $data['seller_id'] = $good['user_id'];
            $data['user_id'] = $user['id'];
            $data['seller_name'] = $good['real_name'];
            $data['seller_phone'] = $good['phone'];
            $data['buyer_name'] = $data['name'];
            $data['buyer_phone'] = $data['phone'];
        }else{
            //买入
            //卖家定金比例
            $earnest = Config::get('site.sell_earnest');
            //卖家抽成比例
            $data['buyer_commission'] = Config::get('site.seller_commission');
            $data['seller_id'] = $user['id'];
            $data['user_id'] = $good['user_id'];
            $data['buyer_name'] = $good['real_name'];
            $data['buyer_phone'] = $good['phone'];
            $data['seller_name'] = $data['name'];
            $data['seller_phone'] = $data['phone'];
        }

        //优惠券
        if (isset($data['coupon_id']) && $data['coupon_id'] > 0) {
            $coupon = $this->Usercoupon->where('id', $data['coupon_id'])->find();
            if (!$coupon || $coupon['status'] != 0) {
                $this->error('优惠券不存在');
            }
            $data['coupon_price'] = $coupon['coupon_price'];
        }
        //计算定金
        $total_money = $good['price'] * $good['num'] * $earnest;//抽成
        $data['earnest'] = $total_money;//买家定金
        $data['price'] = $good['price'];
        $data['total_price'] = $good['price'] * $good['num'];
        $data['title'] = $good['title'];
        $data['image'] = $good['image'];
        $data['selltime'] = $good['selltime'];
        $data['is_seller'] = $good['is_seller'];
        //跳支付，支付保证金
        $result = $this->pay($user,$data,$total_money);
        if($result){
            $this->success('去支付',$result);
        }
        Cache::pull($data['good_id']);
        $this->error('支付暂未开通');

//        //TODO 测试
//        $trade_no = 'wx' . time() . rand(1000, 9999);
//        \db('paylog')->insert([
//            'user_id' => $user->id,
//            'goods' => json_encode($data),
//            'trade_no' => $trade_no,
//            'state' => 1,
//            'type' => 2,
//            'money' => $total_money,
//            'createtime' => time(),
//            'updatetime' => time()
//        ]);
//        $order = db('paylog')->where('trade_no', $trade_no)->find();
//        if (!$order || $order['state'] != 1) { // 如果订单不存在 或者 订单已经支付过了
//            $this->error('支付暂未开通');
//        }
//        db('paylog')->where('id', $order['id'])->update([
//            'pay_time' => date('Y-m-d H:i:s', time()),
//            'state' => 2
//        ]);
//        $this->Order->add(json_decode($order['goods']), $order['user_id'], $trade_no, 11);
//        $this->success('添加成功');
    }

    /**
     * 微信支付
     */
    public function pay($user, $data, $total_money,$type=2)
    {
        //$type 1购物车下单 2直接下单
        $config = $this->config();
        $app = Factory::payment($config);
        $trade_no = 'wx' . time() . rand(1000, 9999);
        $url = Env::get('app.app_url', 'https://admin.danmaimai.cn');
        $result = $app->order->unify([
            'body' => '微信支付',
            'out_trade_no' => $trade_no,
            'total_fee' => $total_money * 100,
            'spbill_create_ip' => '', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $url . '/api/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->openid,
        ]);
        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            $result = $app->jssdk->sdkConfig($result['prepay_id']); //第二次签名
            $result['price'] = (string)($total_money * 100);
            $result['out_trade_no'] = (string)$trade_no;
            $result['date'] = (string)date('Y-m-d H:i:s');
            // 保存订单信息
            \db('paylog')->insert([
                'user_id' => $user->id,
                'goods' => json_encode($data),
                'trade_no' => $trade_no,
                'state' => 1,
                'type' => $type,
                'money' => $total_money,
                'createtime' => time(),
                'updatetime' => time()
            ]);
            $result["orderId"] = $trade_no;
            return $result;
        }
        return false;
    }

    /**
     * 配置
     * @return string[]
     */
    public function config()
    {
        //获取插件
        $config = get_addon_config('epay');
        $config = [
            // 必要配置
            'app_id' => $config['wechat']['miniapp_id'],
            'mch_id' => $config['wechat']['mch_id'],
            'key' => $config['wechat']['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => ROOT_PATH.'addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => ROOT_PATH.'addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径！！！！
            'notify_url' => '',     // 你也可以在下单时单独设置来想覆盖它
        ];
        return $config;
    }

    /**
     * 购物车下单(每条商品生成一条订单)
     */
    public function cart()
    {
        $user = $this->auth->getUser();
        $data = request()->param();
        if (!$data['cart'] || empty($data['name']) || empty($data['phone'])) {
            $this->error('参数不全');
        }
        if (!Validate::regex($data['phone'], "^1\d{10}$")) {
            $this->error(__('请输入正确的手机号'));
        }
        //买家定金比例
        $earnest = Config::get('site.earnest');
        //买家抽成比例
        $buyer_commission = Config::get('site.buyer_commission');
        $arr = [];
        $total_money = 0;
        foreach ($data['cart'] as $v) {
            $cart = $this->Cart->where('id', $v['cart_id'])->find();
            if (!$cart) {
                $this->error(__('请选择商品'));
            }
            $cache = Cache::get($cart['good_id']);
            if($cache){
                $this->error(__('商品已售完'));
            }
            Cache::set($cart['good_id'],$cart['good_id'],3);
            $good = $this->Goods->where('id', $cart['good_id'])->find();
            if (!$good || $good['status'] != 1) {
                $this->error(__('商品不存在或已下架'));
            }
            if ($v['coupon_id'] && $v['coupon_id'] > 0) {
                //判断是否使用优惠券
                $coupon = $this->Usercoupon->where('id', $v['coupon_id'])->find();
                if (!$coupon || $coupon['status'] != 0) {
                    $this->error('优惠券不存在');
                }
                $coupon_price = $coupon['coupon_price'];
            }
            //计算定金
            $money = $good['price'] * $earnest;
            $total_money += $money;
            array_push($arr, [
                'name' => $data['name'],
                'phone' => $data['phone'],
                'seller_id' => $good['user_id'],
                'good_id' => $good['id'],
                'title' => $good['title'],
                'image' => $good['image'],
                'total_price' => $good['price'],
                'earnest' => $money,
                'buyer_commission' => $buyer_commission,
                'coupon_id' => isset($v['coupon_id']) ? $v['coupon_id'] : null,
                'coupon_price' => isset($coupon_price) ? $coupon_price : 0,
            ]);
        }
        //跳支付，支付保证金
//        $result = $this->pay($user,$arr,$total_money,3);
//        if($result){
//            $this->success('去支付',$result);
//        }
//        $this->error('支付暂未开通');

        //TODO 测试
        $trade_no = 'wx' . time() . rand(1000, 9999);
        \db('paylog')->insert([
            'user_id' => $user->id,
            'goods' => json_encode($arr),
            'trade_no' => $trade_no,
            'state' => 1,
            'type' => 2,
            'money' => $total_money,
            'createtime' => time(),
            'updatetime' => time()
        ]);
        $order = db('paylog')->where('trade_no', $trade_no)->find();
        if (!$order || $order['state'] != 1) { // 如果订单不存在 或者 订单已经支付过了
            $this->error('支付暂未开通');
        }
        db('paylog')->where('id', $order['id'])->update([
            'pay_time' => date('Y-m-d H:i:s', time()),
            'state' => 2
        ]);
        $this->Order->adds(json_decode($order['goods']), $order['user_id'],$total_money, $trade_no, 11);
        $this->success('添加成功');
    }

    /**
     * 确认收货
     * @return void
     */
    public function confirm()
    {
        $order_id = request()->param('order_id');
        $user = $this->auth->getUser();
        $order = $this->Order
            ->where(['user_id' => $user->id, 'id' => $order_id])
            ->find();
        if (!$order) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $this->Order->earnestReturn($order,0);
            $this->Order->where('id', $order_id)->update([
                'status' => 2
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('确认收货');
    }

    /**
     * 7天自动收货 定时任务(不用)
     */
    public function selfaction()
    {
        $this->Order
            ->where('status', 1)
            ->where('createtime', '<=', date('Y-m-d H:i:s', time() - 7 * 24 * 3600))
            ->update([
                'status' => 2
            ]);
        $this->success('确认收货');
    }

    /**
     * 退还买家定金 定金-服务费
     */
    public function buyearnest()
    {
        $order = $this->Order
            ->with(['good'])
            ->where('status', 2)
            ->where('buyer_status', 1)
            ->limit(5)
            ->select();
        if (count($order)) {
            foreach ($order as $v) {
                if($v['is_seller'] == 1){//卖出
                    $totalFee = $v['total_price'];
                    $refundFee = $v['earnest'] - $v['service'];
                    $transaction_id = $v['transaction_id'];
                }else{
                    $totalFee = $v['good']['earnest_money'] + $v['good']['exposure_fee'] + $v['good']['referral_fee'] + $v['good']['premium_fee'];
                    $refundFee = $v['good']['earnest_money'] - $v['good']['service'];
                    $transaction_id = $v['good']['transaction_id'];
                }

                $config = $this->config();
                $app = Factory::payment($config);
                $refundNumber = 'tk'.time().rand(100,999);
                // 参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
                $result = $app->refund->byTransactionId($transaction_id, $refundNumber, intval($totalFee * 100), intval($refundFee * 100), [
                    // 可在此处传入其他参数，详细参数见微信支付文档
                    'refund_desc' => '退还定金',
                ]);
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] != 'FAIL'){
                    //修改订单状态
                    $this->Order->where('id',$v['id'])->update([
                        'buyer_status' => 2
                    ]);
                }
            }
        }
        $this->success('成功');
    }

    /**
     * 退还卖家保证金 保证金-服务费
     */
    public function sellearnest()
    {
        $order = $this->Order
            ->with(['good'])
            ->where('status', 2)
            ->where('seller_status', 1)
            ->limit(5)
            ->select();
        if (count($order)) {
            foreach ($order as $v) {
                if($v['is_seller'] == 2){//买入
                    $totalFee = $v['total_price'];
                    $refundFee = $v['earnest'] - $v['service'];
                    $transaction_id = $v['transaction_id'];
                }else{
                    $totalFee = $v['good']['earnest_money'] + $v['good']['exposure_fee'] + $v['good']['referral_fee'] + $v['good']['premium_fee'];
                    $refundFee = $v['good']['earnest_money'] - $v['good']['service'];
                    $transaction_id = $v['good']['transaction_id'];
                }

//                $totalFee = $v['good']->earnest_money;
//                $refundFee = (1-$v['good']->seller_commission)*$v['good']->earnest_money;
                $config = $this->config();
                $app = Factory::payment($config);
                $refundNumber = 'tk'.time().rand(1000,9999);
                // 参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
                $result = $app->refund->byTransactionId($transaction_id, $refundNumber, intval($totalFee * 100), intval($refundFee * 100), [
                    // 可在此处传入其他参数，详细参数见微信支付文档
                    'refund_desc' => '退还保证金',
                ]);
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] != 'FAIL'){
                    //修改订单状态
                    $this->Order->where('id',$v['id'])->update([
                        'seller_status' => 2
                    ]);
                }
            }
        }
        $this->success('成功');
    }

    /**
     * 发货
     */
    public function deliver()
    {
        $order_id = request()->param('order_id');
        if(!$order_id) $this->error('请选择要发货的订单');
        $driver_name = request()->param('driver_name');
        if(!$driver_name) $this->error('请输入司机姓名');
        $driver_phone = request()->param('driver_phone');
        if(!$driver_phone) $this->error('请输入司机电话');
        $plate_number = request()->param('plate_number');
        if(!$plate_number) $this->error('请输入司机车牌号');
        $user_id = $this->auth->id;
        $order = $this->Order
            ->where('id',$order_id)
            ->where('seller_id',$user_id)
            ->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['deliver_status'] != 1){
            $this->error('已发货');
        }
        $this->Order
            ->where('id',$order_id)
            ->update([
                'deliver_status' => 2,
                'driver_name' => $driver_name,
                'driver_phone' => $driver_phone,
                'plate_number' => $plate_number,
            ]);
        $this->success('发货成功');
    }
}
